package com.puhui.lib.http.retrofit;

import android.app.Activity;
import android.content.Intent;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.puhui.lib.base.BaseActivity;
import com.puhui.lib.utils.DMLog;
import com.puhui.lib.utils.JsonUtils;
import com.puhui.lib.utils.NetworkUtils;
import com.puhui.lib.utils.PHConstant;
import com.puhui.lib.utils.MyToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.HttpException;

/**
 * Created by TANGJIAN on 2017/1/28.
 * Description:
 * Modified by TANGJIAN on 2017/1/28.
 */
@SuppressWarnings("all")
public abstract class RequestResponse<T> {
    public RequestResponse() {
    }

    public void onRequestResult(String requestUrl, T result) {

        try {
            DMLog.e(requestUrl);
            DMLog.e(RequestResponse.class.getSimpleName(), result.toString());
            JSONObject jsonObject = new JSONObject(result.toString());

            String code = JsonUtils.getString(jsonObject, "code");
            String message = JsonUtils.getString(jsonObject, "msg");
            String resultJson = JsonUtils.getString(jsonObject, "data");

            Activity activity = ActivityUtils.getTopActivity();
            //如果Token错误，或者超时，则跳转到登录界面  //未通过身份认证，请重新登录
            if ("CommErrCode.Unauthorized".equals(code)) { //退出
                if (null != activity && !activity.isFinishing()) {
                    DMLog.e(HttpManager.class.getSimpleName(), "登录已过期url = " + requestUrl);
                    Intent intent = new Intent(PHConstant.BroadCastReceiver.TOKEN_ERROR);
                    intent.putExtra("message", "登录已过期，请重新登录");
                    intent.putExtra("requestUrl", requestUrl);
                    LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);

                    if (activity instanceof BaseActivity) {
                        ((BaseActivity) activity).stopLoading();
                    }
//                    onFailure(null);
                    return;
                }
            } else if (code.startsWith("CommErrCode.")) {
                if (null != activity && !activity.isFinishing() && !requestUrl.contains("comm-app-version/ios-switch")) {
                    if (activity instanceof BaseActivity) {
                        ((BaseActivity) activity).stopLoading();
                    }
                    return;
                }
            }
            onSuccess(code, message, resultJson);
        } catch (Exception e) {
            e.printStackTrace();
            onFailure(null);
        }
    }

    public void onFailure(Throwable t) {
        Activity activity = ActivityUtils.getTopActivity();
        if (null != activity && !activity.isFinishing()) {
            if (null != t) {
                if (!NetworkUtils.isNetworkAvailable(activity)) {
                    MyToastUtil.getInstance().show("网络连接失败，请稍后重试");
                } else if (t instanceof HttpException) {
                    MyToastUtil.getInstance().show("连接服务器失败");
                } else if (t instanceof SocketTimeoutException) {
                    MyToastUtil.getInstance().show("网络请求超时，请稍后再试");
                } else if (t instanceof ConnectException) {
                    MyToastUtil.getInstance().show("连接服务器失败");
                } else if (t instanceof IOException) {
                    MyToastUtil.getInstance().show("连接服务器失败");
                }
            }
        }
    }

    public void onNetworkError() {
    }

    public abstract void onSuccess(String code, String message, String result);
}


//不要删了，参考
//public abstract class RequestResponse<T, M> {
//    private Activity activity;
//    private String requestUrl;
//    private Class<M> mClazz;
//
//    public RequestResponse(Class<M> clazz) {
//        mClazz = clazz;
//    }
//
//    void onRequestResult(String requestUrl, T result) {
//        if (!StringUtils.isEmpty(this.requestUrl)) {
//            requestUrl = this.requestUrl;
//        }
//        try {
//            DMLog.e(requestUrl);
//            DMLog.e(HttpManager.class.getSimpleName(), result.toString());
//            JSONObject jsonObject = new JSONObject(result.toString());
//            JSONObject apiResDto = JsonUtils.getJsonObject(jsonObject, "apiResDto");
//
//            String code;
//            String message;
//            JSONObject resultJson = null;
//            if (null != apiResDto) {
//                code = JsonUtils.getString(apiResDto, "code");
//                message = JsonUtils.getString(apiResDto, "msg");
//                resultJson = JsonUtils.getJsonObject(apiResDto, "resBizMap");
//            } else {
//                code = JsonUtils.getString(jsonObject, "code");
//                message = JsonUtils.getString(jsonObject, "msg");
//            }
//
////            M m = jsonToBean(resultJson.toString(), mClazz);
//            M m = new Gson().fromJson(resultJson.toString(), mClazz);
//
//            onSuccess(code, message, m);
//        } catch (Exception e) {
//            e.printStackTrace();
//            onFailure(null);
//        }
//    }
//
//    public abstract void onSuccess(String code, String message, M result);
//
//    public static <M> List<M> jsonToBeanList(String json, Class<M> t) throws Exception {
//        List<M> list = new ArrayList<>();
//        JsonParser parser = new JsonParser();
//        JsonArray jsonarray = parser.parse(json).getAsJsonArray();
//        for (JsonElement element : jsonarray
//                ) {
//            list.add(new Gson().fromJson(element, t));
//        }
//        return list;
//    }
//
//    public static <M> M jsonToBean(String json, Class<M> t) throws Exception {
//        JsonParser parser = new JsonParser();
//        JsonElement jsonarray = parser.parse(json).getAsJsonObject();
//        M m = new Gson().fromJson(jsonarray, t);
//        return m;
//    }
//}

//使用
//Observable<String> loginResult = HttpManager.getInstance().createApiService().login(httpParams.getRequestBody());
//        HttpManager.getInstance().toSubscribe(mView.currentActivity(),
//                loginResult, HttpManager.getSubscriber(new RequestResponse<String, UserLoginInfo>(UserLoginInfo.class) {});
